package com.rmondjone.androidcamerademo

import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.media.MediaPlayer
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.View
import android.view.WindowManager
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.otaliastudios.cameraview.CameraListener
import com.otaliastudios.cameraview.PictureResult
import com.otaliastudios.cameraview.controls.Facing
import com.rmondjone.androidcamerademo.bean.CameraType
import com.rmondjone.camera.BaseActivity
import com.rmondjone.camera.BitmapUtils
import com.rmondjone.face.FaceConsultationActivity
import com.rmondjone.utils.setClickListener
import com.rmondjone.view.WebDialog
import kotlinx.android.synthetic.main.activity_camre_layout.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

/**
 * copyright：
 * @author：anthui creation date： .
 * @since: 1.0.0
 * @describe:
 */
class PhotoActivity : BaseActivity() {

    lateinit var typeAdapter: TypeAdapter

    var typeBean: TypeBean? = null
    var player: MediaPlayer? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_camre_layout)

        camera.setLifecycleOwner(this)
//        camera.playSounds = false
        camera.addCameraListener(object : CameraListener() {


            override fun onPictureTaken(result: PictureResult) {
                super.onPictureTaken(result)
                takePicture(result.data)
            }


        })

        //拍照
        layout_pic.setClickListener {

            camera.takePicture();

        }
        iv_pic.setClickListener {
            camera.toggleFacing()
        }
        //切换摄像头
        layout_change.setClickListener {
            camera.toggleFacing()
        }



        layout_helper.setClickListener {

            var url: String = ""

            when (intent.getIntExtra("type", CameraType.CAMERA_TYPE_FMIAN_ZHEN)) {
                CameraType.CAMERA_TYPE_FMIAN_ZHEN -> {
//http://baike.aiaibangzhu.com/index/index/help?name=mianzhen_help
//http://baike.aiaibangzhu.com/index/index/help?name=xuewei_help
                    url = "mianzhen_help"

                }
                CameraType.CAMERA_TYPE_XUE_WEI -> {
                    url = "xuewei_help"

                }
                CameraType.CAMERA_TYPE_SHE_ZHEN -> {
                    url = "shezhen_help"

                }
                else -> {
                }
            }

            url.isNotEmpty().let {

                val currentUrl = "http://baike.aiaibangzhu.com/index/index/help?name=$url"

                WebDialog().apply {
                    this.url = currentUrl
                    show(supportFragmentManager)
                }


            }

        }

        iv_back.setClickListener {
            finish()
        }
        setTips()
    }

    private fun setTips() {

        when (intent.getIntExtra("type", CameraType.CAMERA_TYPE_FMIAN_ZHEN)) {
            CameraType.CAMERA_TYPE_FMIAN_ZHEN -> {

                val url = "https://baike.aiaibangzhu.com/uploads/20201124/d345a388a00776f0e222a26181378870.png"
                Glide.with(this).load(url).into(mask_img)

                tv_tips.text = "请拍摄正脸照，素颜出镜，摘掉眼镜保持面部无遮挡物"
                tv_title.text = "请平视摄像头"

                player = MediaPlayer.create(this, R.raw.mian).apply {
                    start()
                }


            }
            CameraType.CAMERA_TYPE_XUE_WEI -> {

                rv_type.apply {
                    visibility = View.VISIBLE
                    layoutManager = LinearLayoutManager(this@PhotoActivity).apply {
                        orientation = LinearLayoutManager.HORIZONTAL
                    }

                    typeAdapter = TypeAdapter()
                    adapter = typeAdapter
                    typeAdapter.setOnItemClickListener { adapter, view, position ->
                        typeAdapter.itemCheckPosit = position
                        checkType(typeAdapter.data[position])
                        typeAdapter.notifyDataSetChanged()
                    }
                }

                MainActivity.data?.firstOrNull()?.let {
                    typeAdapter.itemCheckPosit = 0
                    checkType(it)
                    typeAdapter.setNewData(MainActivity.data)

                }

            }
            CameraType.CAMERA_TYPE_SHE_ZHEN -> {
                camera.zoom = 0.2f

                val url = "http://baike.aiaibangzhu.com/uploads/20201130/867d193f3a7dd47a93065bc610f9059e.png"
                Glide.with(this).load(url).into(mask_img)
                tv_tips.text = "舌体放松，舌面平展，舌尖略向下，口张大不要用力"
                tv_title.text = "拍摄舌面照片"
                player = MediaPlayer.create(this, R.raw.she_tou).apply {
                    start()
                }
            }
            else -> {
            }
        }


    }

    private fun checkType(typeBean: TypeBean) {

        //是否需要前置
        var isFont = typeBean.photo_type == 1

//        if (camera.facing == Facing.FRONT) {
//            if (!isFont) {
//                camera.toggleFacing()
//            }
//        } else {
//            if (isFont) {
//                camera.toggleFacing()
//            }
//        }
//        this.typeBean?.isCheck = false
//        typeBean.isCheck = true
        this.typeBean = typeBean
        Log.e("msg", "url----------- " + typeBean.image)
        tv_title.text = ""
        tv_tips.text = typeBean.description ?: ""
        Glide.with(this).load(typeBean.image).into(mask_img)
    }

    fun takePicture(data: ByteArray) {

        GlobalScope.launch(Dispatchers.IO) {

            val bitmap = BitmapFactory.decodeByteArray(data, 0, data.size)

            val cameraPath = Environment.getExternalStorageDirectory().path + File.separator + "DCIM" + File.separator + "Camera"
            //相册文件夹
            val cameraFolder = File(cameraPath)
            if (!cameraFolder.exists()) {
                cameraFolder.mkdirs()
            }
            //保存的图片文件
            val simpleDateFormat = SimpleDateFormat("yyyyMMdd_HHmmss")
            val imagePath = cameraFolder.absolutePath + File.separator + "IMG_" + simpleDateFormat.format(Date()) + ".jpg"

            val capBitMap = capBitMap(bitmap)

            val changeBitMap = changeBitMap(capBitMap)

            BitmapUtils.saveBitmap(changeBitMap, imagePath)

            withContext(Dispatchers.Main) {

                var intExtra = intent.getIntExtra("type", CameraType.CAMERA_TYPE_FMIAN_ZHEN)
                when (intExtra) {
                    CameraType.CAMERA_TYPE_SHE_ZHEN,
                    CameraType.CAMERA_TYPE_FMIAN_ZHEN -> {
                        var intent = Intent(this@PhotoActivity, FaceConsultationActivity::class.java)
                        intent.putExtra("path", imagePath)
                        intent.putExtra("type", intExtra)
                        finish()
                        startActivity(intent)
//                        launch {
//                            delay(300)
//
//
//                        }
                    }

                    CameraType.CAMERA_TYPE_XUE_WEI -> {
                        typeBean?.let {
                            var intent = Intent(this@PhotoActivity, FaceActivity::class.java)
                            intent.putExtra("path", imagePath)
                            intent.putExtra("typeId", it.id)
                            finish()
                            startActivity(intent)

                        }
                    }
                    else -> {
                    }
                }


            }

        }
    }

    fun changeBitMap(bitmap: Bitmap): Bitmap {
        Log.e("msg", "m----------原比例 width2-- " + bitmap.width + "  height-- " + bitmap.height)

        val width = bitmap.width
        val widthRate: Float
        widthRate = 750f / width
        val matrix = Matrix()



        if (camera.facing == Facing.FRONT) {
            matrix.postScale(-1 * widthRate, widthRate)
        } else {
            matrix.postScale(widthRate, widthRate)
        }

        val bitmaps = Bitmap.createBitmap(bitmap, 0, 0,
                bitmap.width, bitmap.height, matrix, true)

        Log.e("msg", "m---------- width-- " + bitmaps.width + "  height-- " + bitmaps.height)
        return bitmaps

    }

    override fun onStart() {
        super.onStart()
//        camera.onStart()
    }

    override fun onResume() {
        super.onResume()


    }

    override fun onPause() {
        super.onPause()
        player?.stop()

    }

    override fun finish() {

        layout_prent.visibility = View.VISIBLE
        super.finish()

    }


    override fun onDestroy() {
        super.onDestroy()
        player?.release()

    }

    fun capBitMap(bitmap: Bitmap): Bitmap {


        val width = bitmap.width * 1f
        val height = bitmap.height * 1f

        var imageRate = getImageRate()

        var realWidth = imageRate * height
        Log.e("msg", "实width--  " + width + "  height-- " + height + "  需要真实宽度 " + realWidth + "  bili-- " + imageRate)

        var x = 0f
        if (width > realWidth) {
            x = (width - realWidth) / 2
        } else {
            realWidth = width
        }

        val bitmaps = Bitmap.createBitmap(bitmap, x.toInt(), 0,
                realWidth.toInt(), height.toInt())

        return bitmaps

    }

    private fun getImageRate(): Float {
        val width: Float = 560.dp / camera.height
        return width
    }

}